package ym.controller.back.website;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ym.pojo.Announcement;
import ym.service.AnnouncementService;
import ym.vo.BaseResult;
import ym.vo.CustomMultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

/**
 * 后台公告
 */
@RestController
@CrossOrigin
@RequestMapping("/back/announcement")
public class AnnouncementCon {
    @Autowired
    private AnnouncementService announcementService;

    /**
     * 新增
     *
     * @param announcement
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('/website')")
    public BaseResult add(Announcement announcement) {
        announcementService.add(announcement);
        return BaseResult.ok();
    }

    /**
     * 修改
     *
     * @param announcement
     * @return
     */
    @PostMapping("/update")
    public BaseResult update(Announcement announcement) {
        announcementService.update(announcement);
        return BaseResult.ok();
    }

    /**
     * 删除
     *
     * @param announcementId
     * @return
     */
    @DeleteMapping("/delete")
    public BaseResult delete(Integer announcementId) {
        announcementService.delete(announcementId);
        return BaseResult.ok();
    }

    /**
     * 根据id查询
     *
     * @param announcementId
     * @return
     */
    @GetMapping("/findById")
    public BaseResult findById(Integer announcementId) {
        Announcement announcement = announcementService.findById(announcementId);
        return BaseResult.ok(announcement);
    }

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping("/findAll")
    public BaseResult findAll() {
        List<Announcement> announcements = announcementService.findAll();
        return BaseResult.ok(announcements);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @PreAuthorize("hasAnyAuthority('/website')")
    @GetMapping("/search")
    public BaseResult search(String search, int page, int size) {
        Page<Announcement> brandPage = announcementService.search(search, page, size);
        return BaseResult.ok(brandPage);
    }

    /**
     * 导出Excel文件
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public BaseResult exportExcel(HttpServletResponse response) throws IOException {
        announcementService.exportExcel(response);
        return BaseResult.ok();
    }

    /**
     * 导入Excel文件
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    public BaseResult importExcel(MultipartFile file) throws IOException {
        boolean flag = announcementService.importExcel(file);
        if (flag) {
            return BaseResult.ok();
        } else {
            return new BaseResult(601, "导入失败", null);
        }
    }

    /**
     * 根据url导入Excel文件
     *
     * @param fileUrl
     * @return
     */
    @PostMapping("/importByUrl")
    public BaseResult importExcelByUrl(@RequestParam("fileUrl") String fileUrl) throws IOException, InterruptedException {
        MultipartFile file = downloadFileFromUrl(fileUrl);
        boolean flag = announcementService.importExcel(file);
        if (file != null) {
            if (flag) {
                return BaseResult.ok();
            } else {
                return new BaseResult<>(601, "导入失败", null);
            }
        } else {
            return new BaseResult<>(601, "文件下载失败", null);
        }
    }

    //根据url下载文件
    private MultipartFile downloadFileFromUrl(String fileUrl) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileUrl))
                .build();
        HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (response.statusCode() == 200) {
            byte[] fileBytes = response.body();
            String fileName = getFileNameFromUrl(fileUrl);
            return new CustomMultipartFile(fileName, fileBytes);
        }
        return null;
    }

    //从url中获取文件名
    private String getFileNameFromUrl(String fileUrl) {
        int lastIndex = fileUrl.lastIndexOf("/");
        if (lastIndex != -1) {
            return fileUrl.substring(lastIndex + 1);
        }
        return "unknown_file";
    }
}
